package coollemon.view;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.Iterator;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class PhotoChooser extends JDialog implements ActionListener,ChangeListener,MouseMotionListener,MouseListener
{
	//TypeChooser tc = new TypeChooser();
	int buttonWidth = 80,buttonHight = 32, firstS = 40, step = 90;
	JButton open = new JButton("open"), change = new JButton("change"), ok = new JButton("OK"),export = new JButton("export");
	JButton jpeg = new JButton("jpeg"), jpg = new JButton("jpg"), png = new JButton("png"), gif = new JButton("gif");
	JButton reset = new JButton(new ImageIcon(MainFrame.class.getResource("/coollemon/res/png-0028.png")));
	String typeChosed = "jpg";
	JSlider jsb = new JSlider();
	JPanel north = new JPanel();
	JTextField width = new JTextField(10);
	JTextField hight = new JTextField(10);
	JSeparator jsp = new JSeparator();
	JLabel wLabel,hLabel;
	PhotoScrollPane msp = PhotoScrollPane.getInstance();
	FileDialog fileOpen = new FileDialog(this,"Open File",FileDialog.LOAD);
	FileDialog fileExport = new FileDialog(this,"setting File",FileDialog.SAVE);
	static PhotoChooser instance;
	PhotoChooser()
	{
		jpeg.addActionListener(this);
		jpg.addActionListener(this);
		png.addActionListener(this);
		gif.addActionListener(this);
		open.addActionListener(this);
		change.addActionListener(this);
		ok.addActionListener(this);
		export.addActionListener(this);
		jsb.addChangeListener(this);
		reset.addActionListener(this);
		msp.mainPanel.addMouseListener(msp.mainPanel);
		msp.mainPanel.addMouseMotionListener(msp.mainPanel);
		//tc.add(jpeg);
		//tc.add(jpg);
		//tc.add(png);
		//tc.add(gif);
		jpeg.setBounds(5, 5, 60, 25);
		jpg.setBounds(70, 5, 60, 25);
		png.setBounds(5, 35, 60, 25);
		gif.setBounds(70, 35, 60, 25);
		wLabel = new JLabel(Integer.toString(128));
		hLabel = new JLabel(Integer.toString(128));
		north.setLayout(null);
		north.setPreferredSize(new Dimension(900,32));
		north.add(open);
		//north.add(jsb);
		north.add(width);
		north.add(hight);
		north.add(wLabel);
		north.add(hLabel);
		north.add(change);
		north.add(ok);
		north.add(export);
		north.add(reset);
		reset.setBounds(0, 0, buttonHight, buttonHight);
		open.setBounds(firstS, 0, buttonWidth, buttonHight);
		JLabel tempLabel = new JLabel("width:");
		north.add(tempLabel);
		tempLabel.setBounds(firstS+step, 0, buttonWidth, buttonHight);
		width.setBounds(firstS+(int)(1.5*step), 0, buttonWidth/2, buttonHight);
		wLabel.setBounds(firstS+(int)(6*step), 0, buttonWidth/2, buttonHight);
		//width.setVisible(false);
		tempLabel = new JLabel("hight:");
		north.add(tempLabel);
		tempLabel.setBounds(firstS+2*step, 0, buttonWidth, buttonHight);
		hight.setBounds(firstS+(int)(2.5*step), 0, buttonWidth/2, buttonHight);
		tempLabel = new JLabel("*");
		north.add(tempLabel);
		tempLabel.setBounds(firstS+(int)(6.4*step), 0, buttonWidth/2, buttonHight);
		hLabel.setBounds(firstS+(int)(6.6*step), 0, buttonWidth/2, buttonHight);
		//hight.setVisible(false);
		change.setBounds(firstS+3*step, 0, buttonWidth, buttonHight);
		ok.setBounds(firstS+4*step, 0, buttonWidth, buttonHight);
		export.setBounds(firstS+5*step, 0, buttonWidth, buttonHight);
		jsp.setBounds(0, 0, 30, 5);
		this.setSize(700, 600);
		this.setTitle("Magic Photo");
		this.add("North",north);
		this.add("Center",msp);
		this.add("South",jsb);
		URL url = MainFrame.class.getResource("/coollemon/res/png-0029.png");
		this.setIconImage((new ImageIcon(url)).getImage());
		//this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setAlwaysOnTop(true);

		Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
		// center the frame in the physical screen
		this.setLocation((d.width - this.getWidth()) / 2,
				(d.height - this.getHeight()) / 2);
		
		this.setVisible(true);
	}
	public static PhotoChooser getInstance()
	{
		if(instance == null)
		{
			instance = new PhotoChooser();
		}
		return instance;
	}
	public static void main(String args[]) {
		PhotoChooser.getInstance();
	}
	public BufferedImage outFile(File f)
	{
        ImageWriter   writer   =   null;
        BufferedImage imageScan;
        if(typeChosed != "png")
        	imageScan = new BufferedImage((int)(msp.mainPanel.image.getWidth(this)*Math.pow((double)4, ((double)msp.mainPanel.zoom-50)/50)),
				(int)(msp.mainPanel.image.getHeight(this)*Math.pow((double)4, ((double)msp.mainPanel.zoom-50)/50)), BufferedImage.TYPE_INT_RGB);
        else
        	imageScan = new BufferedImage((int)(msp.mainPanel.image.getWidth(this)*Math.pow((double)4, ((double)msp.mainPanel.zoom-50)/50)),
				(int)(msp.mainPanel.image.getHeight(this)*Math.pow((double)4, ((double)msp.mainPanel.zoom-50)/50)), BufferedImage.TYPE_4BYTE_ABGR);
        imageScan.getGraphics().drawImage(   
        		msp.mainPanel.image.getScaledInstance(imageScan.getWidth(), imageScan.getHeight(),   
                        Image.SCALE_SMOOTH), 0, 0, null);
        if(msp.mainPanel.x+msp.mainPanel.w < imageScan.getWidth() && msp.mainPanel.y+msp.mainPanel.h < imageScan.getHeight())
        {
        	imageScan = imageScan.getSubimage(msp.mainPanel.x, msp.mainPanel.y, msp.mainPanel.w, msp.mainPanel.h);
        }
        ImageTypeSpecifier   type   =   
                ImageTypeSpecifier.createFromRenderedImage(imageScan);
	        Iterator   iter   =   ImageIO.getImageWriters(type,   typeChosed);
	        if(typeChosed == "jpeg")iter   =   ImageIO.getImageWriters(type,   "jpg");
	        if   (iter.hasNext())   {   
	                writer   =   (ImageWriter)iter.next();
	        }   
	        if   (writer   ==   null)   {   
	                return imageScan;   
	        }   
	        IIOImage   iioImage   =   new   IIOImage(imageScan,   null,   null);   
	        ImageWriteParam   param   =   writer.getDefaultWriteParam();
	        if(typeChosed == "jpg")
	        {
	        	param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); 
	        	param.setCompressionQuality(1.0f);
	        }
	        if(typeChosed == "jpeg")
	        {
	        	param.setCompressionMode(ImageWriteParam.MODE_DEFAULT);
	        }
	        ImageOutputStream outputStream;
			try {
				outputStream = ImageIO.createImageOutputStream(f);   
	            writer.setOutput(outputStream);   
	            writer.write(null,   iioImage,   param);
	            outputStream.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
        }
		return	imageScan;
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if(e.getSource() == open)
		{
			this.setAlwaysOnTop(false);
			fileOpen.setAlwaysOnTop(true);
			fileOpen.setVisible(true);
			if(fileOpen.getFile() != null)
			{
				File f = new File(fileOpen.getDirectory(),fileOpen.getFile());
				msp.mainPanel.openfile(f);
				msp.setViewportView(msp.mainPanel);
			}
			this.setAlwaysOnTop(true);
		}
		if(e.getSource() == ok)
		{
			DataView.getInstance().con.setIcon(MainFrame.getInstance().user.filepath.getAbsolutePath()+"\\"
												+DataView.getInstance().con.getId()+".jpg");
			//System.out.print(DataView.class.getResource(DataView.getInstance().con.getIcon()).);
			File f = new File(DataView.getInstance().con.getIcon());
			BufferedImage imageScan = this.outFile(f);
			//DataView.getInstance().photo.setIcon(null);
			//DataView.getInstance().con.setIcon("D:/"+DataView.getInstance().con.getId()+"."+typeChosed);
			DataView.getInstance().photo.setIcon(new ImageIcon(imageScan));
		}
		if(e.getSource() == change)
		{
			if((width.getText().equals(""))||(hight.getText().equals("")))return;
			try{
			this.msp.mainPanel.w = Math.abs((new Integer(width.getText())).intValue());
			this.msp.mainPanel.h = Math.abs((new Integer(hight.getText())).intValue());
			this.wLabel.setText(Integer.toString(this.msp.mainPanel.w));
			this.hLabel.setText(Integer.toString(this.msp.mainPanel.h));
			}catch(Exception e1)
			{
				
			}
			repaint();
		}
		if(e.getSource() == export)
		{
			this.setAlwaysOnTop(false);
			fileExport.setAlwaysOnTop(true);
			fileExport.setVisible(true);
			if(fileExport.getFile() != null)
			{
				File f = new File(fileExport.getDirectory(),fileExport.getFile()+"."+typeChosed);
				this.outFile(f);
			}
			this.setAlwaysOnTop(true);
		}
		if(e.getSource() == reset)
		{
			this.msp.mainPanel.x = 0;
			this.msp.mainPanel.y = 0;
			jsb.setValue(50);
			msp.mainPanel.zoom = 50;
			if(msp.mainPanel.image != null)msp.mainPanel.setSize();
			msp.mainPanel.repaint();
			msp.setViewportView(msp.mainPanel);
		}
	}
	@Override
	public void stateChanged(ChangeEvent e) {
		// TODO Auto-generated method stub
		if(e.getSource() == jsb)
		{
			msp.mainPanel.zoom = jsb.getValue();
			if(msp.mainPanel.image != null)msp.mainPanel.setSize();
			msp.mainPanel.repaint();
			msp.setViewportView(msp.mainPanel);
		}
	}
	@Override
	public void mouseDragged(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void mouseMoved(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void mouseClicked(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void mousePressed(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void mouseReleased(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}
}
